﻿/* 光标操作
 * Caret.setRange(id, start, end):设置id的文字选区
 * Caret.getRange(id):得到id选区{ start: x, end: y }
 * Caret.setText (id, text):设置id选区文字
 * Caret.getText(id):得到id选区文字
*/
var LG=(function(lg){
    var _caret={};
    _caret.setRange=function(id,start,end){
        var d = document, input = d.createElement("input");
        isStandard = "selectionStart" in input;
        isSupported = isStandard || (input = d.selection) && !!input.createRange();

        var o = document.getElementById(id);
        if (isStandard)
            o.setSelectionRange(start, end);
        else if (isSupported) {
            var t = o.createTextRange();
            end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
            start -= o.value.slice(0, start).split("\n").length - 1;
            t.move("character", start), t.moveEnd("character", end), t.select();
        }
    };
    _caret.getRange=function(id){
        var d = document, input = d.createElement("input");
        isStandard = "selectionStart" in input;
        isSupported = isStandard || (input = d.selection) && !!input.createRange();
        var o = document.getElementById(id);
        isTA = o.nodeName.toLowerCase() == "textarea";

        if (isStandard)
            return { start: o.selectionStart, end: o.selectionEnd };
        else if (isSupported) {
            var s = (o.focus(), d.selection.createRange()), r, start, end, value;
            if (s.parentElement() != o)
                return { start: 0, end: 0 };
            if (isTA ? (r = s.duplicate()).moveToElementText(o) : r = o.createTextRange(), !isTA)
                return r.setEndPoint("EndToStart", s), { start: r.text.length, end: r.text.length + s.text.length };
            for (var $ = "[###]"; (value = o.value).indexOf($) + 1; $ += $);
            r.setEndPoint("StartToEnd", s), r.text = $ + r.text, end = o.value.indexOf($);
            s.text = $, start = o.value.indexOf($);
            if (d.execCommand && d.queryCommandSupported("Undo"))
                for (r = 3; --r; d.execCommand("Undo"));
            return o.value = value, this.setRange(id,start, end), { start: start, end: end };
        }
        return { start: 0, end: 0 };
    };
    _caret.setText=function(id,text){
        var d = document, input = d.createElement("input");
        isStandard = "selectionStart" in input;
        isSupported = isStandard || (input = d.selection) && !!input.createRange();
        var o = document.getElementById(id);
        var o = this.getRange(id), i = document.getElementById(id), s = i.value;
        i.value = s.slice(0, o.start) + text + s.slice(o.end);
        this.setRange(id,o.start += text.length, o.start);
    };
    _caret.getText=function(id){
        var o = this.getRange(id);
        
        return document.getElementById(id).value.slice(o.start, o.end);        
    }
    lg.Caret=_caret ;
    return lg;
}(LG||{}));